Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '',
    visitDate: '',
    currentDate: Date.now(),
    maxDate: Date.now() + 3 * 24 * 60 * 60 * 1000,
    houseId: '',
    name: '',
    gender: 0,
    mobile: ''
  },
  onLoad () {
    this.getHouseList()
  },
  // 获取能保修的房屋列表
  async getHouseList () {
    const res = await wx.$http.get('/house')
    if (res.code !== 10000) return wx.$utils.toast()
    this.setData({
      houseList: res.data
    })
  },
  chooseHouse (e) {
    this.setData({
      houseInfo: e.detail.name,
      houseId: e.detail.id
    })
  },
  chooseDate (e) {
    this.setData({
      visitDate: wx.$utils.formatDate(e.detail)
    })
    this.closeDateLayer()
  },
  verifyHouse () {
    const valid = this.data.houseId !== ''
    // 验证结果提示
    if (!valid) wx.$utils.toast('请选择房屋信息!')
    // 返回验证结果
    return valid
  },
  // 验证业主姓名（必须为汉字）
  verifyName () {
    // 正则表达式
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    // 验证业主姓名
    const valid = reg.test(this.data.name.trim())
    // 验证结果提示
    if (!valid) wx.$utils.toast('请填写真实中文姓名!')
    // 返回验证结果
    return valid
  },

  verifyMobile () {
    // 验证手机号
    const reg = /^[1][3-8][0-9]{9}$/
    const valid = reg.test(this.data.mobile)
    // 验证结果提示
    if (!valid) wx.$utils.toast('请填写正确的手机号码!')
    // 返回验证结果
    return valid
  },
  async submit () {
    if (!this.verifyHouse()) return
    if (!this.verifyName()) return
    if (!this.verifyMobile()) return

    const { houseId, name, gender, mobile, visitDate } = this.data
    const res = await wx.$http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    if (res.code !== 10000) return wx.$utils.toast()
    this.goPassport(res.data.id)
  },
  openHouseLayer () {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer () {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer () {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer () {
    this.setData({ dateLayerVisible: false })
  },
  goPassport (id) {
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id
    })
  }
})
